package com.tang.portal.component.harbor.core;

import com.alibaba.fastjson2.JSON;
import com.tang.common.properties.HarborConfigProperties;
import com.tang.framework.core.cache.CoolTeaConfig;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author tang jun liang
 * @Date 2023/6/21 9:55
 */

public abstract class HarborBaseService {


    protected HarborConfigProperties harborConfigProperties;

    protected final HttpClient httpClient;


    public HarborBaseService(CloseableHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public HarborBaseService() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
    }


    protected String execute(HttpUriRequest httpUriRequest) throws IOException {
        processRequest(httpUriRequest);
        HttpResponse response = httpClient.execute(httpUriRequest);
        return EntityUtils.toString(response.getEntity());
    }


    private void processRequest(HttpUriRequest httpUriRequest) {
        if (Objects.isNull(harborConfigProperties)){
            harborConfigProperties = getHarborConfigProperties();
        }
        httpUriRequest.setHeader("X-Accept-Vulnerabilities", "application/vnd.security.vulnerability.report; version=1.1, application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0");
        httpUriRequest.setHeader(HttpHeaders.AUTHORIZATION, getBasicAuthHeaderValue(harborConfigProperties.getUsername(), harborConfigProperties.getPassword()));

    }

    protected HarborConfigProperties getHarborConfigProperties() {
        return CoolTeaConfig.getConfig(HarborConfigProperties.class);
    }

    protected String getBasicAuthHeaderValue(String username, String password) {
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
        return "Basic " + new String(encodedAuth);
    }



}
